<template>
  <div class="health-manage-container">
    <h1 class="page-title">🩺 宠物健康检测管理</h1>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="宠物名称">
          <el-input v-model="searchForm.petName" placeholder="请输入宠物名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="检测类型">
          <el-input v-model="searchForm.checkType" placeholder="请输入检测类型" clearable></el-input>
        </el-form-item>
        <el-form-item label="健康状态">
          <el-select v-model="searchForm.healthStatus" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="异常" :value="2"></el-option>
            <el-option label="待观察" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生姓名">
          <el-input v-model="searchForm.doctorName" placeholder="请输入医生姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="检测日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="体重范围(kg)">
          <el-input-number v-model="searchForm.minWeight" :min="0" :precision="1" placeholder="最小" controls-position="right" style="width: 130px;"></el-input-number>
          <span style="margin: 0 10px;">-</span>
          <el-input-number v-model="searchForm.maxWeight" :min="0" :precision="1" placeholder="最大" controls-position="right" style="width: 130px;"></el-input-number>
        </el-form-item>
        <el-form-item label="体温范围(°C)">
          <el-input-number v-model="searchForm.minTemperature" :min="0" :precision="1" placeholder="最低" controls-position="right" style="width: 130px;"></el-input-number>
          <span style="margin: 0 10px;">-</span>
          <el-input-number v-model="searchForm.maxTemperature" :min="0" :precision="1" placeholder="最高" controls-position="right" style="width: 130px;"></el-input-number>
        </el-form-item>
        <el-form-item label="心率范围(次/分)">
          <el-input-number v-model="searchForm.minHeartRate" :min="0" placeholder="最低" controls-position="right" style="width: 130px;"></el-input-number>
          <span style="margin: 0 10px;">-</span>
          <el-input-number v-model="searchForm.maxHeartRate" :min="0" placeholder="最高" controls-position="right" style="width: 130px;"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增检测记录</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 健康记录列表 -->
    <el-card style="margin-top: 20px;">
      <el-table :data="healthList" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="petName" label="宠物名称"></el-table-column>
        <el-table-column prop="checkDate" label="检测日期" width="160"></el-table-column>
        <el-table-column prop="checkType" label="检测类型"></el-table-column>
        <el-table-column prop="weight" label="体重(kg)" width="100"></el-table-column>
        <el-table-column prop="temperature" label="体温(°C)" width="100"></el-table-column>
        <el-table-column prop="heartRate" label="心率" width="100">
          <template slot-scope="scope">
            {{ scope.row.heartRate }}次/分
          </template>
        </el-table-column>
        <el-table-column prop="status" label="健康状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.statusName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="doctorName" label="检测医生"></el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="mini" type="primary" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
              <el-button size="mini" type="warning" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog title="健康检测详情" :visible.sync="viewDialogVisible" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="宠物名称">{{ viewHealthData.petName }}</el-descriptions-item>
        <el-descriptions-item label="检测日期">{{ viewHealthData.checkDate }}</el-descriptions-item>
        <el-descriptions-item label="检测类型">{{ viewHealthData.checkType }}</el-descriptions-item>
        <el-descriptions-item label="检测医生">{{ viewHealthData.doctorName || viewHealthData.veterinarian }}</el-descriptions-item>
        <el-descriptions-item label="体重">{{ viewHealthData.weight }}kg</el-descriptions-item>
        <el-descriptions-item label="体温">{{ viewHealthData.temperature }}°C</el-descriptions-item>
        <el-descriptions-item label="心率">{{ viewHealthData.heartRate }}次/分</el-descriptions-item>
        <el-descriptions-item label="呼吸频率">{{ viewHealthData.respiratoryRate }}次/分</el-descriptions-item>
        <el-descriptions-item label="健康状态">
          <el-tag :type="getStatusType(viewHealthData.status)">{{ viewHealthData.statusName || viewHealthData.healthStatusText }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下次检查日期">{{ viewHealthData.nextCheckDate }}</el-descriptions-item>
        <el-descriptions-item label="症状" :span="2">{{ viewHealthData.symptoms || '无' }}</el-descriptions-item>
        <el-descriptions-item label="诊断" :span="2">{{ viewHealthData.diagnosis || '无' }}</el-descriptions-item>
        <el-descriptions-item label="治疗方案" :span="2">{{ viewHealthData.treatment || '无' }}</el-descriptions-item>
        <el-descriptions-item label="医生建议" :span="2">{{ viewHealthData.suggestion || viewHealthData.notes || '无' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer">
        <el-button type="primary" @click="viewDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px">
      <el-form :model="healthForm" :rules="healthRules" ref="healthForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择宠物" prop="petId">
              <el-select v-model="healthForm.petId" placeholder="请选择宠物" filterable style="width: 100%">
                <el-option v-for="pet in petList" :key="pet.id" :label="pet.name" :value="pet.id">
                  <span>{{ pet.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ pet.breed }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测日期" prop="checkDate">
              <el-date-picker
                v-model="healthForm.checkDate"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检测类型" prop="checkType">
              <el-input v-model="healthForm.checkType" placeholder="如：常规体检、疫苗接种"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测医生" prop="doctorName">
              <el-input v-model="healthForm.doctorName" placeholder="请输入医生姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="体重(kg)">
              <el-input-number v-model="healthForm.weight" :min="0" :max="200" :precision="1" controls-position="right" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="体温(°C)">
              <el-input-number v-model="healthForm.temperature" :min="0" :max="50" :precision="1" controls-position="right" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="心率(次/分)">
              <el-input-number v-model="healthForm.heartRate" :min="0" :max="300" controls-position="right" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="检测项目">
          <el-input v-model="healthForm.items" placeholder="请输入检测项目，如：血常规、尿常规"></el-input>
        </el-form-item>

        <el-form-item label="检测结果">
          <el-input type="textarea" v-model="healthForm.result"
                    :rows="3" placeholder="请输入检测结果"></el-input>
        </el-form-item>

        <el-form-item label="健康状态" prop="status">
          <el-radio-group v-model="healthForm.status">
            <el-radio label="normal">正常</el-radio>
            <el-radio label="abnormal">异常</el-radio>
            <el-radio label="observe">待观察</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="医生建议">
          <el-input type="textarea" v-model="healthForm.suggestion"
                    :rows="3" placeholder="请输入医生建议"></el-input>
        </el-form-item>

        <el-form-item label="上传报告">
          <el-upload
            action="#"
            :auto-upload="false"
            :limit="3">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持 pdf, jpg, png 格式，不超过 10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminHealthList } from '@/api/health'
import healthApi from '@/api/health'
import petApi from '@/api/pet'

export default {
  name: 'HealthManage',
  data () {
    return {
      searchForm: {
        petName: '',
        checkType: '',
        healthStatus: null,
        doctorName: '',
        dateRange: null,
        minTemperature: null,
        maxTemperature: null,
        minWeight: null,
        maxWeight: null,
        minHeartRate: null,
        maxHeartRate: null
      },
      healthList: [],
      petList: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      viewDialogVisible: false,
      viewHealthData: {},
      dialogTitle: '新增检测记录',
      healthForm: {
        petId: null,
        checkDate: '',
        checkType: '',
        doctorName: '',
        weight: 0,
        temperature: 0,
        heartRate: 0,
        items: '',
        result: '',
        status: 'normal',
        suggestion: ''
      },
      healthRules: {
        petId: [{ required: true, message: '请选择宠物', trigger: 'change' }],
        checkDate: [{ required: true, message: '请选择检测日期', trigger: 'change' }],
        checkType: [{ required: true, message: '请输入检测类型', trigger: 'blur' }],
        status: [{ required: true, message: '请选择健康状态', trigger: 'change' }]
      }
    }
  },
  created () {
    this.loadHealthList()
    this.loadPetList()
  },
  methods: {
    async loadHealthList () {
      this.loading = true
      try {
        // 构建查询参数
        const params = {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        }
        
        // 添加筛选条件
        if (this.searchForm.petName) {
          params.petName = this.searchForm.petName
        }
        if (this.searchForm.checkType) {
          params.checkType = this.searchForm.checkType
        }
        if (this.searchForm.healthStatus !== null && this.searchForm.healthStatus !== '') {
          params.healthStatus = this.searchForm.healthStatus
        }
        if (this.searchForm.doctorName) {
          params.doctorName = this.searchForm.doctorName
        }
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startDate = this.searchForm.dateRange[0]
          params.endDate = this.searchForm.dateRange[1]
        }
        if (this.searchForm.minTemperature !== null && this.searchForm.minTemperature !== '') {
          params.minTemperature = this.searchForm.minTemperature
        }
        if (this.searchForm.maxTemperature !== null && this.searchForm.maxTemperature !== '') {
          params.maxTemperature = this.searchForm.maxTemperature
        }
        if (this.searchForm.minWeight !== null && this.searchForm.minWeight !== '') {
          params.minWeight = this.searchForm.minWeight
        }
        if (this.searchForm.maxWeight !== null && this.searchForm.maxWeight !== '') {
          params.maxWeight = this.searchForm.maxWeight
        }
        if (this.searchForm.minHeartRate !== null && this.searchForm.minHeartRate !== '') {
          params.minHeartRate = this.searchForm.minHeartRate
        }
        if (this.searchForm.maxHeartRate !== null && this.searchForm.maxHeartRate !== '') {
          params.maxHeartRate = this.searchForm.maxHeartRate
        }
        
        console.log('健康检测查询参数:', params)
        const res = await getAdminHealthList(params)
        console.log('健康检测返回数据:', res)
        
        // 处理响应数据
        const data = (res.data && res.data.records) || (res.data && res.data.list) || res.data || []
        this.healthList = data.map(item => ({
          id: item.id,
          petName: item.petName || item.pet_name || '未知',
          checkDate: item.checkDate || item.check_date || '',
          checkType: item.checkType || item.check_type || '常规检查',
          weight: item.weight || 0,
          temperature: item.temperature || 0,
          heartRate: item.heartRate || item.heart_rate || 0,
          respiratoryRate: item.respiratoryRate || item.respiratory_rate || 0,
          healthStatus: item.healthStatus || item.health_status,
          statusName: item.healthStatusText || item.health_status_text || this.mapHealthStatus(item.healthStatus || item.health_status),
          doctorName: item.doctorName || item.doctor_name || item.veterinarian || '-',
          diagnosis: item.diagnosis || '',
          treatment: item.treatment || '',
          remark: item.remark || ''
        }))
        
        // 更新分页信息
        this.pagination.total = (res.data && res.data.total) || data.length || 0
      } catch (error) {
        console.error('加载失败:', error)
        this.$message.error('加载失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    async loadPetList () {
      try {
        const res = await petApi.getPetList({ page: 1, size: 100 })
        this.petList = res.data || []
      } catch (error) {
        console.error('加载宠物列表失败', error)
      }
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.loadHealthList()
    },
    handleReset () {
      this.searchForm = {
        petName: '',
        checkType: '',
        healthStatus: null,
        doctorName: '',
        dateRange: null,
        minTemperature: null,
        maxTemperature: null,
        minWeight: null,
        maxWeight: null,
        minHeartRate: null,
        maxHeartRate: null
      }
      this.pagination.currentPage = 1
      this.loadHealthList()
    },
    handleAdd () {
      this.dialogTitle = '新增检测记录'
      this.healthForm = {
        petId: null,
        checkDate: '',
        checkType: '',
        doctorName: '',
        weight: 0,
        temperature: 0,
        heartRate: 0,
        items: '',
        result: '',
        status: 'normal',
        suggestion: ''
      }
      this.dialogVisible = true
    },
    async handleView (row) {
      try {
        const res = await healthApi.getHealthDetail(row.id)
        const data = res.data || row
        this.viewHealthData = {
          ...data,
          petName: data.petname || data.petName,
          checkDate: data.checkdate || data.checkDate,
          weight: data.weight,
          temperature: data.temperature,
          heartRate: data.heartrate || data.heartRate,
          respiratoryRate: data.respiratoryrate || data.respiratoryRate,
          symptoms: data.symptoms,
          diagnosis: data.diagnosis,
          treatment: data.treatment,
          nextCheckDate: data.nextcheckdate || data.nextCheckDate,
          status: this.mapHealthStatus(data.healthstatus || data.healthStatus),
          statusName: data.healthstatustext || data.healthStatusText,
          checkType: data.checkType || data.check_type || '常规检查',
          doctorName: data.veterinarian || data.doctorName || '-',
          notes: data.notes
        }
        this.viewDialogVisible = true
      } catch (error) {
        this.$message.error('加载详情失败：' + (error.message || '未知错误'))
      }
    },
    async handleEdit (row) {
      try {
        const res = await healthApi.getHealthDetail(row.id)
        this.dialogTitle = '编辑检测记录'
        const data = res.data
        this.healthForm = {
          id: data.id,
          petId: data.petid || data.petId,
          checkDate: data.checkdate || data.checkDate,
          weight: data.weight,
          temperature: data.temperature,
          heartRate: data.heartrate || data.heartRate,
          checkType: data.checkType || data.check_type || '常规检查',
          doctorName: data.veterinarian || data.doctorName || '',
          items: data.items || '',
          result: data.result || '',
          status: this.mapHealthStatus(data.healthstatus || data.healthStatus),
          suggestion: data.notes || data.suggestion || ''
        }
        this.dialogVisible = true
      } catch (error) {
        this.$message.error('加载详情失败：' + (error.message || '未知错误'))
      }
    },
    handleDelete (row) {
      this.$confirm(`确认删除该检测记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await healthApi.deleteHealth(row.id)
          this.$message.success('删除成功')
          this.loadHealthList()
        } catch (error) {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
        }
      })
    },
    handleSubmit () {
      this.$refs.healthForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.healthForm.id) {
              await healthApi.updateHealth(this.healthForm.id, this.healthForm)
            } else {
              await healthApi.addHealth(this.healthForm)
            }
            this.$message.success('操作成功')
            this.dialogVisible = false
            this.loadHealthList()
          } catch (error) {
            this.$message.error('操作失败：' + (error.message || '未知错误'))
          }
        }
      })
    },
    getStatusType (status) {
      const typeMap = {
        'normal': 'success',
        'abnormal': 'danger',
        'observe': 'warning'
      }
      return typeMap[status] || 'info'
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.loadHealthList()
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.loadHealthList()
    },
    mapHealthStatus (status) {
      const statusMap = { 1: 'normal', 2: 'observe', 3: 'observe', 4: 'abnormal' }
      return statusMap[status] || 'normal'
    }
  }
}
</script>

<style scoped>
.health-manage-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>
